package com.ocn.li.scmdy.modules.sys.controller;

/**
 * @author ：Li9527
 * @date ：Created in 2019-10-29 9:27
 * @description：${description}
 * @modified By：
 * @version: 1.0.0
 */

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ocn.li.scmdy.common.exception.MyException;
import com.ocn.li.scmdy.common.utils.QueryExt;
import com.ocn.li.scmdy.common.utils.R;
import com.ocn.li.scmdy.common.validator.ValidatorUtils;
import com.ocn.li.scmdy.modules.app.annotation.Login;
import com.ocn.li.scmdy.modules.app.entity.UserEntity;
import com.ocn.li.scmdy.modules.app.form.CoinDetailCount;
import com.ocn.li.scmdy.modules.app.form.UpdateCoinForm;
import com.ocn.li.scmdy.modules.app.service.CoinDetailService;
import com.ocn.li.scmdy.modules.app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/coin")
@Slf4j
public class CoinDetailController extends AbstractController {

    @Autowired
    private CoinDetailService coinDetailService;

    @Autowired
    private UserService userService;

    @Login
    @GetMapping("/coinDetail")
    public R coinDetail(@RequestParam Map<String, Object> params){
        Page page =null;
        CoinDetailCount coinDetailCount = null;
        params.put("orderByField", "create_time");
        params.put("isAsc", false);
        page = coinDetailService.selectPageCoin(new QueryExt(params));
        coinDetailCount = coinDetailService.selectCastCoinCounts(new QueryExt(params));
        coinDetailCount.setAddCoin(coinDetailService.selectGetCoinCounts(new QueryExt(params)));
        coinDetailCount.setCountCoin(0l);
        return R.ok().put("page",page).put("coinDetailCount",coinDetailCount);
    }

    @Login
    @PostMapping("/updateCoin")
    public R updateCoin(@RequestBody UpdateCoinForm form){
        try {
            ValidatorUtils.validateEntity(form);
            UserEntity user = userService.selectOne(new EntityWrapper<UserEntity>().eq("mobile",form.getMobile()));
            if(form.getType() == 1){
                if(form.getNum() < 0 ){
                    throw new MyException("后门充值不能为负");
                }
            }else{
                if(user.getCoin() - form.getNum() < 0){
                    throw new MyException("余额不足不能扣款");
                }
            }
            Integer integer = userService.updateCoin(form);
            if(integer ==1){
                return  R.ok("积分增加成功");
            }else if(integer ==0){
                return  R.ok("积分扣除成功");
            }

        }catch (Exception e){
            return  R.error(e.getMessage());
        }
        return R.error("积分操作失败");
    }

}
